import numpy as np
import os
import cv2
from tqdm import tqdm     # python 进度条库

from PIL import Image, ImageDraw, ImageFont


def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text((left, top), text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)


image_folder_dir="C:\\Users\\Jackey\\Desktop\\video"
fps = 6     # fps: frame per seconde 每秒帧数，数值可根据需要进行调整
size = (800, 448)     # (width, height) 数值可根据需要进行调整
target_size = (640, 360)
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')     # 编码为 mp4v 格式，注意此处字母为小写，大写会报错
video = cv2.VideoWriter("C:\\Users\\Jackey\\Desktop\\video\\ATS.mp4", fourcc, fps,  (640, 360*3), isColor=True)

image_list1 = sorted([name for name in os.listdir(image_folder_dir) if name.endswith('.png') and 'L4E0' in name])     # 获取文件夹下所有格式为 jpg 图像的图像名，并按时间戳进行排序
image_list2 = sorted([name for name in os.listdir(image_folder_dir) if name.endswith('.png') and 'L4E2' in name])     # 获取文件夹下所有格式为 jpg 图像的图像名，并按时间戳进行排序
image_list3 = sorted([name for name in os.listdir(image_folder_dir) if name.endswith('.jpg') and 'L0E9' in name])     # 获取文件夹下所有格式为 jpg 图像的图像名，并按时间戳进行排序
print(len(image_list1), len(image_list2), len(image_list1))

with tqdm(total=len(image_list1), desc='处理进度', leave=True, ncols=100, unit='图', unit_scale=True) as pbar:
	for i in range(len(image_list1)):     # 遍历 image_list 中所有图像并添加进度条
		pbar.update(1)
		image1_path = os.path.join(image_folder_dir, image_list1[i])     # 获取图像的全路经
		image1 = cv2.imread(image1_path)     # 读取图像
		image1 = cv2.resize(image1, target_size)	
		image1 = cv2ImgAddText(image1, '水下', 500, 20, textColor= (30, 250, 250), textSize=40)
		image2_path = os.path.join(image_folder_dir, image_list2[i])     # 获取图像的全路经
		image2 = cv2.imread(image2_path)     # 读取图像
		image2 = cv2.resize(image2, target_size)
		image2 = cv2ImgAddText(image2, '泥位', 500, 20, textColor= (30, 250, 250), textSize=40)
		image3_path = os.path.join(image_folder_dir, image_list3[i])     # 获取图像的全路经
		image3 = cv2.imread(image3_path)     # 读取图像
		image3 = cv2.resize(image3, target_size)
		image3 = cv2ImgAddText(image3, '水面', 500, 20, textColor= (30, 250, 250), textSize=40)
		height, width, bytesPerComponent = image1.shape
		image = np.empty([height*3,width,3],'uint8')
		image[0:height,:,:] = image3
		image[height:height*2,:,:] = image1
		image[height*2:height*3,:,:] = image2
		# image[height:height *2,:,:] = image2.copy()
		# image[height*2:height*3,:,:] = image3.copy()
		video.write(image)     # 将图像写入视频

video.release()
cv2.destroyAllWindows()
